﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using XCSerialPort;
using System.Text;

using System.Drawing;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.Configuration;

namespace XC153_ISP_Maintenanc
{
    public partial class MainWindow : Window
    {
        private ObservableCollection<UsbDeviceInfo> usbDevices = new ObservableCollection<UsbDeviceInfo>();

        // 修改为支持三个阶段的监控结果
        private Dictionary<string, Dictionary<string, List<BootMonitorResult>>> stageMonitorResults = new Dictionary<string, Dictionary<string, List<BootMonitorResult>>>();

        private Dictionary<string, List<Dictionary<string, List<BootMonitorResult>>>> stageMonitorResultsByLoop
    = new Dictionary<string, List<Dictionary<string, List<BootMonitorResult>>>>();
        ISerialPortManager serialPortManager;
        private readonly Lazy<ISerialPortManager> _lazySerialPort;
        private readonly Lazy<IPageactions> _lazyPageActions;
        private ISerialPortManager SerialPort => _lazySerialPort.Value;
        private IPageactions PageActions => _lazyPageActions.Value;

        List<RegisterInfo> allRegisters = RegisterInfoData.GetRegisterInfos();

        // 添加监控状态控制变量
        private bool isBootMonitoring = false;
        private bool isStreamMonitoring = false;
        private bool isSensorMonitoring = false;
        private bool isAllMonitoring = false;
        private CancellationTokenSource cancellationTokenSource;
        // 定义全局变量
        private List<RegisterInfo> _allRegisters = new List<RegisterInfo>();

        public MainWindow()
        {
            InitializeComponent();
            serialPortManager = new SerialPort_Usb_RegisterManager();
            NavigationService.Initialize(serialPortManager);
            // 初始化所有懒加载字段
            _lazySerialPort = new Lazy<ISerialPortManager>(() =>
                XCSerialPort.NavigationService.GetSerialPort());
            _lazyPageActions = new Lazy<IPageactions>(() =>
                new Pageactions(SerialPort));

            // 初始化三个阶段的结果字典
            stageMonitorResults.Add("Boot", new Dictionary<string, List<BootMonitorResult>>());
            stageMonitorResults.Add("Stream", new Dictionary<string, List<BootMonitorResult>>());
            stageMonitorResults.Add("Sensor", new Dictionary<string, List<BootMonitorResult>>());

            cancellationTokenSource = new CancellationTokenSource();
            // 初始化_allRegisters为默认值
            //_allRegisters = RegisterInfoData.GetRegisterInfos();
            InitializeData();
            // 初始化配置状态显示
            UpdateConfigStatus(); // 添加这行
            InitializeVersionInfo();
            LoadFirmwareVersion();
            StartBlinkingAnimation();
        }

        private void StartBlinkingAnimation()
        {
            // 开始闪烁动画
            var storyboard = (System.Windows.Media.Animation.Storyboard)this.Resources["BlinkingAnimation"];
            storyboard.Begin(FirmwareVersionText, true);
        }
        private void LoadFirmwareVersion()
        {
            try
            {
                // 从app.config读取固件版本号
                string firmwareVersion = ConfigurationManager.AppSettings["FirmwareVersion"];

                if (!string.IsNullOrEmpty(firmwareVersion))
                {
                    FirmwareVersionText.Text = firmwareVersion;
                }
                else
                {
                    FirmwareVersionText.Text = "未知版本";
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"读取配置失败: {ex.Message}");
                FirmwareVersionText.Text = "配置错误";
            }
        }

        // 在程序集信息中定义编译时版本
        private static readonly string BuildVersion = $"v{DateTime.Now:yyyy.MM.dd.HHmm}";

        private void InitializeVersionInfo()
        {
            try
            {
                // 直接使用编译时确定的版本号
                txtVersion.Text = $"版本号: {BuildVersion}";
                Console.WriteLine($"[版本信息] 编译版本: {BuildVersion}");
            }
            catch (Exception ex)
            {
                txtVersion.Text = "版本号: v1.0.0";
                Console.WriteLine($"[版本信息] 设置版本号失败: {ex.Message}");
            }
        }

        private void InitializeData()
        {
            // 初始化USB设备列表
            cmbUsbDevices.ItemsSource = usbDevices;
        }

        // USB设备操作事件
        private void RefreshUsbDevices_Click(object sender, RoutedEventArgs e)
        {
            string msg;
            var ports = SerialPort.GetSerialPorts(out msg);
            // 刷新USB设备列表
            usbDevices.Clear();
            // 这里添加实际扫描USB设备的代码
            foreach (var port in ports)
            {
                // 解析端口信息为 AdbDevice
                var parts = port.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length >= 1)
                {
                    usbDevices.Add(new UsbDeviceInfo
                    {
                        DeviceId = parts[0],
                        DeviceName = parts.Length > 1 ? parts[1] : parts[0],
                        Status = "device"
                    });
                }
            }
            // 更新 ComboBox 的数据源
            cmbUsbDevices.ItemsSource = usbDevices;

            // 如果列表不为空，选择第一个设备
            if (usbDevices.Count > 0)
            {
                cmbUsbDevices.SelectedIndex = 0; // 选择第一个设备
            }
            AddLog("USB设备列表已刷新");
        }

        private void OpenDevice_Click(object sender, RoutedEventArgs e)
        {
            

            // 获取当前选择的设备类型
           var currentControlType = GetCurrentDeviceControlType();
            switch (currentControlType)
            {   
                case DeviceControlType.USB:
                    {
                        if (cmbUsbDevices.SelectedItem == null)
                        {
                            MessageBox.Show("请先选择要打开的USB设备", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                            return;
                        }
                        string msg;
                        // 打开设备逻辑
                        var selectedIndex = cmbUsbDevices.SelectedIndex;
                        SerialPort.SetDeviceConfig(selectedIndex);
                        bool isOpened = SerialPort.Open(out msg);
                        AddLog($"已打开设备: {selectedIndex} {isOpened} {msg}");
                    }
                    break;
                case DeviceControlType.I2C:
                    {
                        string busText = cmbI2CBus.Text;
                        if (int.TryParse(busText, out int busNumber))
                        {
                            SerialPort.SetDeviceConfig(busNumber);
                        }
                        string msg;
                        bool isOpened = SerialPort.Open(out msg);
                        AddLog($"已打开设备: I2C {isOpened} {msg}");
                    }
                    break;
                default:
                    break;
            }
        }


        private void CloseDevice_Click(object sender, RoutedEventArgs e)
        {
            string msg;
            SerialPort.Close(out msg);
            // 关闭设备逻辑
            AddLog($"设备已关闭 {msg}");
        }

        // Boot阶段监控事件
        private async void StartBootMonitoring_Click(object sender, RoutedEventArgs e)
        {
            // 添加设备检查
            if (!CheckDeviceOpened("Boot阶段监控"))
            {
                return;
            }

            // 显示带固件版本号的确认对话框
            var confirmDialog = new ExportConfirmDialog();
            confirmDialog.Owner = this; // 设置父窗口

            bool? result = confirmDialog.ShowDialog();
            if (result == true && confirmDialog.ExportConfirmed)
            {

                if (!int.TryParse(txtBootLoopCount.Text, out int loopCount) ||
                    !int.TryParse(txtBootInterval.Text, out int interval))
                {
                    MessageBox.Show("请输入有效的循环次数和间隔时间", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (isBootMonitoring)
                {
                    MessageBox.Show("Boot监控已在运行中", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 启动Boot监控逻辑
                AddLog($"启动Boot阶段监控 - 循环次数: {loopCount}, 间隔: {interval}ms");

                //// 模拟监控过程
                //if (chkAutoLogBoot.IsChecked == true)
                //{
                //    AddLog("Boot监控: 自动记录已启用");
                //}

                isBootMonitoring = true;
                UpdateButtonStates();

                try
                {
                    await Task.Run(() => ExecuteBootMonitoring(loopCount, interval));
                    MessageBox.Show("Boot阶段监控已完成", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (OperationCanceledException)
                {
                    AddLog("Boot阶段监控已取消");
                }
                finally
                {
                    isBootMonitoring = false;
                    UpdateButtonStates();
                }
            }
            else
            {
                // 用户取消操作
                MessageBox.Show("导出操作已取消", "提示",
                               MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }




        private void StopBootMonitoring_Click(object sender, RoutedEventArgs e)
        {
            if (isBootMonitoring)
            {
                cancellationTokenSource.Cancel();
                AddLog("正在停止Boot阶段监控...");
            }
            else
            {
                AddLog("Boot阶段监控未运行");
            }
        }




        // 出图阶段监控事件
        private async void StartStreamMonitoring_Click(object sender, RoutedEventArgs e)
        {

            // 添加设备检查
            if (!CheckDeviceOpened("出图阶段监控"))
            {
                return;
            }
            // 显示带固件版本号的确认对话框
            var confirmDialog = new ExportConfirmDialog();
            confirmDialog.Owner = this; // 设置父窗口

            bool? result = confirmDialog.ShowDialog();

            if (result == true && confirmDialog.ExportConfirmed)
            {

                if (!int.TryParse(txtStreamLoopCount.Text, out int loopCount) ||
                    !int.TryParse(txtStreamInterval.Text, out int interval))
                {
                    MessageBox.Show("请输入有效的循环次数和间隔时间", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (isStreamMonitoring)
                {
                    MessageBox.Show("出图监控已在运行中", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 启动出图监控逻辑
                AddLog($"启动出图阶段监控 - 循环次数: {loopCount}, 间隔: {interval}ms");

                

                isStreamMonitoring = true;
                UpdateButtonStates();

                try
                {
                    await Task.Run(() => ExecuteStreamMonitoring(loopCount, interval));
                    MessageBox.Show("出图阶段监控已完成", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (OperationCanceledException)
                {
                    AddLog("出图阶段监控已取消");
                }
                finally
                {
                    isStreamMonitoring = false;
                    UpdateButtonStates();
                }
            }
            else
            {
                // 用户取消操作
                MessageBox.Show("导出操作已取消", "提示",
                               MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void StopStreamMonitoring_Click(object sender, RoutedEventArgs e)
        {
            if (isStreamMonitoring)
            {
                cancellationTokenSource.Cancel();
                AddLog("正在停止出图阶段监控...");
            }
            else
            {
                AddLog("出图阶段监控未运行");
            }
        }


        // Sensor监控事件
        private async void StartSensorMonitoring_Click(object sender, RoutedEventArgs e)
        {   // 添加设备检查
            if (!CheckDeviceOpened("Sensor监控"))
            {
                return;
            }
            // 显示带固件版本号的确认对话框
            var confirmDialog = new ExportConfirmDialog();
            confirmDialog.Owner = this; // 设置父窗口

            bool? result = confirmDialog.ShowDialog();

            if (result == true && confirmDialog.ExportConfirmed)
            {
                
                if (!int.TryParse(txtSensorLoopCount.Text, out int loopCount) ||
                    !int.TryParse(txtSensorInterval.Text, out int interval))
                {
                    MessageBox.Show("请输入有效的循环次数和间隔时间", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (isSensorMonitoring)
                {
                    MessageBox.Show("Sensor监控已在运行中", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                // 启动Sensor监控逻辑
                AddLog($"启动Sensor监控 - 循环次数: {loopCount}, 间隔: {interval}ms");

              

                isSensorMonitoring = true;
                UpdateButtonStates();

                try
                {
                    await Task.Run(() => ExecuteSensorMonitoring(loopCount, interval));
                    MessageBox.Show("Sensor监控已完成", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (OperationCanceledException)
                {
                    AddLog("Sensor监控已取消");
                }
                finally
                {
                    isSensorMonitoring = false;
                    UpdateButtonStates();
                }
            }
            else
            {
                // 用户取消操作
                MessageBox.Show("导出操作已取消", "提示",
                               MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void StopSensorMonitoring_Click(object sender, RoutedEventArgs e)
        {
            if (isSensorMonitoring)
            {
                cancellationTokenSource.Cancel();
                AddLog("正在停止Sensor监控...");
            }
            else
            {
                AddLog("Sensor监控未运行");
            }
        }


        // 通用日志操作
        private void ClearLog_Click(object sender, RoutedEventArgs e)
        {
            txtLogOutput.Clear();
            AddLog("日志已清空");
        }

        private void ExportAllLog_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                FileName = $"All_Log_{DateTime.Now:yyyyMMdd_HHmmss}.txt"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                File.WriteAllText(saveFileDialog.FileName, txtLogOutput.Text);
                AddLog($"所有日志已导出到: {saveFileDialog.FileName}");
            }
        }

        private void AddLog(string message)
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            Dispatcher.Invoke(() =>
            {
                if (txtLogOutput !=null)
                {
                    txtLogOutput.AppendText($"[{timestamp}] {message}\n");
                    txtLogOutput.ScrollToEnd();
                }
               
            });
        }



        private void BaseAddress_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 使用动态寄存器源
                var currentRegisters = GetCurrentRegisters();
                string configSource = GetConfigSourceDescription();
                AddLog($"=== 查看地址信息 ({configSource}) ===");

                // 按LogInfo和Category双重分组，确保同一LogInfo在不同阶段都能显示
                var groupedRegisters = currentRegisters  // 修改这里：使用 currentRegisters
                    .GroupBy(r => new { r.LogInfo, r.Category })  // 关键修改：双重分组
                    .Select(g => new
                    {
                        LogInfo = g.Key.LogInfo,
                        Category = g.Key.Category,
                        FirstRegister = g.First(),
                        FieldCount = g.Count()
                    })
                    .ToList();

                // 按类别统计
                var bootGroups = groupedRegisters.Where(g => g.Category == "Boot阶段").ToList();
                var streamGroups = groupedRegisters.Where(g => g.Category == "出图阶段").ToList();
                var sensorGroups = groupedRegisters.Where(g => g.Category == "Sensor阶段").ToList();
                var hostGroups = groupedRegisters.Where(g => g.Category == "主机交互").ToList();

                AddLog("=== 寄存器地址信息统计 ===");
                AddLog($"Boot阶段寄存器组: {bootGroups.Count} 个");
                AddLog($"出图阶段寄存器组: {streamGroups.Count} 个");
                AddLog($"Sensor阶段寄存器组: {sensorGroups.Count} 个");
                AddLog($"主机交互寄存器组: {hostGroups.Count} 个");
                AddLog($"总计: {groupedRegisters.Count} 个寄存器组");

                // 显示Boot阶段寄存器详细信息（按组显示）
                AddLog("=== Boot阶段寄存器详情 ===");
                foreach (var group in bootGroups)
                {
                    AddLog($"{group.LogInfo} -> {group.FirstRegister.RegisterAddress} ({group.FirstRegister.BitWidth}位) - {group.FieldCount}个字段");
                }

                // 显示出图阶段寄存器详细信息（按组显示）
                AddLog("=== 出图阶段寄存器详情 ===");
                foreach (var group in streamGroups)
                {
                    AddLog($"{group.LogInfo} -> {group.FirstRegister.RegisterAddress} ({group.FirstRegister.BitWidth}位) - {group.FieldCount}个字段");
                }

                // 显示Sensor阶段寄存器详细信息（按组显示）
                AddLog("=== Sensor阶段寄存器详情 ===");
                foreach (var group in sensorGroups)
                {
                    AddLog($"{group.LogInfo} -> {group.FirstRegister.RegisterAddress} ({group.FirstRegister.BitWidth}位) - {group.FieldCount}个字段");
                }

                // 显示主机交互寄存器详细信息（按组显示）
                AddLog("=== 主机交互寄存器详情 ===");
                foreach (var group in hostGroups)
                {
                    AddLog($"{group.LogInfo} -> {group.FirstRegister.RegisterAddress} ({group.FirstRegister.BitWidth}位) - {group.FieldCount}个字段");
                }

                AddLog("=== 地址计算完成 ===");
            }
            catch (Exception ex)
            {
                AddLog($"查看地址信息出错: {ex.Message}");
            }
        }

        private void TxtbaseAddress_TextChanged(object sender, TextChangedEventArgs e)
        {
            
            string baseAddressText = txtbaseAddress.Text.Trim();
            UpdateBaseAddress(baseAddressText);
        }


        // 方法：更新基地址
        public void UpdateBaseAddress(string baseAddressText)
        {
            try
            {
                // 去除空格
                baseAddressText = baseAddressText?.Trim();

                // 如果输入为空，跳过
                if (string.IsNullOrEmpty(baseAddressText))
                    return;

                // 移除可能的"0x"前缀
                if (baseAddressText.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                {
                    baseAddressText = baseAddressText.Substring(2);
                }

                // 尝试解析为16进制数
                if (uint.TryParse(baseAddressText, NumberStyles.HexNumber, null, out uint baseAddress))
                {
                    // 更新当前使用的寄存器地址
                    UpdateCurrentRegistersBaseAddress(baseAddress);
                    string configSource = GetConfigSourceDescription();
                    AddLog($"基地址已更新为: 0x{baseAddress:X8}，已应用到{configSource}");
                }
                else
                {
                    AddLog($"基地址格式错误: {baseAddressText}，请输入有效的16进制地址");
                }
            }
            catch (Exception ex)
            {
                AddLog($"基地址更新出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取当前应该使用的寄存器列表
        /// </summary>
        private List<RegisterInfo> GetCurrentRegisters()
        {
            return _allRegisters != null && _allRegisters.Count > 0 ? _allRegisters : allRegisters;
        }

        /// <summary>
        /// 更新当前使用的寄存器的基地址（按实际位宽分配）
        /// </summary>
        private void UpdateCurrentRegistersBaseAddress(uint baseAddress)
        {
            var currentRegisters = GetCurrentRegisters();
            uint currentAddress = baseAddress;

            // 按 Category 和 LogInfo 分组，确保每个阶段的相同名称寄存器组独立分配地址
            var groupedRegisters = currentRegisters
                .GroupBy(r => new { r.Category, r.LogInfo }) // 使用复合键
                .ToList();

            foreach (var group in groupedRegisters)
            {
                var firstRegister = group.First();
                int byteCount = (firstRegister.BitWidth + 7) / 8;

                // 特殊处理数组寄存器
                if (group.Key.LogInfo == "resetverd1[10]")
                {
                    byteCount = 0x28; // 40字节，10个32位整数
                }
                else
                {
                    // 如果LogInfo中包含位宽信息，也进行解析
                    if (group.Key.LogInfo.Contains("[7:0]") || group.Key.LogInfo.Contains("[7]"))
                        byteCount = 1;
                    else if (group.Key.LogInfo.Contains("[15:0]") || group.Key.LogInfo.Contains("[15]"))
                        byteCount = 2;
                    else if (group.Key.LogInfo.Contains("[23:0]") || group.Key.LogInfo.Contains("[23]"))
                        byteCount = 3;
                    else if (group.Key.LogInfo.Contains("[31:0]") || group.Key.LogInfo.Contains("[31]"))
                        byteCount = 4;
                }

                uint endAddress = currentAddress + (uint)byteCount - 1;

                // 设置地址范围
                string addressRange;
                if (byteCount > 1) // 如果超过1字节，使用地址范围
                {
                    addressRange = $"0x{currentAddress:X8}-0x{endAddress:X8}";
                }
                else // 单字节
                {
                    addressRange = $"0x{currentAddress:X8}";
                }

                // 为组内的所有寄存器设置相同的地址
                foreach (var register in group)
                {
                    register.RegisterAddress = addressRange;
                    register.SortAddress = currentAddress; // 设置排序地址为起始地址
                }

                // 下一个寄存器从当前地址 + 字节数开始
                currentAddress += (uint)byteCount;
            }

            // 记录地址分配信息
            AddLog($"地址分配完成: 从 0x{baseAddress:X8} 到 0x{currentAddress:X8}, 共 {groupedRegisters.Count} 个寄存器组");
        }

        /// <summary>
        /// 执行Boot阶段监控 - 修改版，支持多循环记录
        /// </summary>
        private void ExecuteBootMonitoring(int loopCount, int interval)
        {
            try
            {
                // 使用动态寄存器源
                var currentRegisters = GetCurrentRegisters();
                string configSource = GetConfigSourceDescription();
                AddLog($"Boot监控使用: {configSource}");

                // 初始化多循环结果存储
                if (!stageMonitorResultsByLoop.ContainsKey("Boot"))
                {
                    stageMonitorResultsByLoop["Boot"] = new List<Dictionary<string, List<BootMonitorResult>>>();
                }
                stageMonitorResultsByLoop["Boot"].Clear();

                // 过滤出Boot阶段的寄存器，排除resetverd1[10]
                var bootRegisters = currentRegisters
                    .Where(r => r.Category == "Boot阶段" && !r.LogInfo.Contains("resetverd1"))
                    .ToList();

                // 按LogInfo分组（相同的寄存器名）
                var groupedRegisters = bootRegisters
                    .GroupBy(r => r.LogInfo)
                    .ToList();

                for (int i = 0; i < loopCount; i++)
                {
                    // 检查取消请求
                    if (cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        AddLog("Boot监控被取消");
                        cancellationTokenSource.Token.ThrowIfCancellationRequested();
                    }

                    AddLog($"Boot监控第 {i + 1} 轮开始");

                    // 为当前循环创建新的结果字典
                    var currentLoopResults = new Dictionary<string, List<BootMonitorResult>>();

                    foreach (var registerGroup in groupedRegisters)
                    {
                        // 修改Process方法，传入当前循环的结果字典
                        ProcessBootRegisterGroupForLoop(registerGroup.Key, registerGroup.ToList(), currentLoopResults, i);
                    }

                    // 将当前循环的结果添加到总结果中
                    stageMonitorResultsByLoop["Boot"].Add(currentLoopResults);

                    // 等待间隔时间
                    if (i < loopCount - 1)
                    {
                        for (int waitTime = 0; waitTime < interval; waitTime += 100)
                        {
                            if (cancellationTokenSource.Token.IsCancellationRequested)
                            {
                                AddLog("Boot监控被取消");
                                cancellationTokenSource.Token.ThrowIfCancellationRequested();
                            }
                            System.Threading.Thread.Sleep(Math.Min(100, interval - waitTime));
                        }
                    }

                    AddLog($"Boot监控第 {i + 1} 轮完成");
                }

                AddLog($"Boot阶段监控完成，共 {loopCount} 轮数据");
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                AddLog($"Boot监控执行出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 执行出图阶段监控 - 修改版，支持多循环记录
        /// </summary>
        private void ExecuteStreamMonitoring(int loopCount, int interval)
        {
            try
            {
                //添加出图阶段 是否在ℹ️2c上需要设置的寄存器
                SetStreamOnRegister();
                // 使用动态寄存器源
                var currentRegisters = GetCurrentRegisters();
                string configSource = GetConfigSourceDescription();
                AddLog($"出图监控使用: {configSource}");

                // 初始化多循环结果存储
                if (!stageMonitorResultsByLoop.ContainsKey("Stream"))
                {
                    stageMonitorResultsByLoop["Stream"] = new List<Dictionary<string, List<BootMonitorResult>>>();
                }
                stageMonitorResultsByLoop["Stream"].Clear();

                // 过滤出出图阶段的寄存器，排除resetverd1[10] - 使用 currentRegisters
                var streamRegisters = currentRegisters
                    .Where(r => r.Category == "出图阶段" && !r.LogInfo.Contains("resetverd1"))
                    .ToList();

                // 按LogInfo分组（相同的寄存器名）
                var groupedRegisters = streamRegisters
                    .GroupBy(r => r.LogInfo)
                    .ToList();

                for (int i = 0; i < loopCount; i++)
                {
                    // 检查取消请求
                    if (cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        AddLog("出图监控被取消");
                        cancellationTokenSource.Token.ThrowIfCancellationRequested();
                    }

                    AddLog($"出图监控第 {i + 1} 轮开始");

                    // 为当前循环创建新的结果字典
                    var currentLoopResults = new Dictionary<string, List<BootMonitorResult>>();

                    foreach (var registerGroup in groupedRegisters)
                    {
                        // 修改Process方法，传入当前循环的结果字典
                        ProcessStreamRegisterGroupForLoop(registerGroup.Key, registerGroup.ToList(), currentLoopResults, i);
                    }

                    // 将当前循环的结果添加到总结果中
                    stageMonitorResultsByLoop["Stream"].Add(currentLoopResults);

                    // 等待间隔时间
                    if (i < loopCount - 1)
                    {
                        for (int waitTime = 0; waitTime < interval; waitTime += 100)
                        {
                            if (cancellationTokenSource.Token.IsCancellationRequested)
                            {
                                AddLog("出图监控被取消");
                                cancellationTokenSource.Token.ThrowIfCancellationRequested();
                            }
                            System.Threading.Thread.Sleep(Math.Min(100, interval - waitTime));
                        }
                    }

                    AddLog($"出图监控第 {i + 1} 轮完成");
                }

                AddLog($"出图阶段监控完成，共 {loopCount} 轮数据");
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                AddLog($"出图监控执行出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 执行Sensor监控 - 修改版，支持多循环记录
        /// </summary>
        private void ExecuteSensorMonitoring(int loopCount, int interval)
        {
            try
            {
                // 使用动态寄存器源
                var currentRegisters = GetCurrentRegisters();
                string configSource = GetConfigSourceDescription();
                AddLog($"Sensor监控使用: {configSource}");

                // 初始化多循环结果存储
                if (!stageMonitorResultsByLoop.ContainsKey("Sensor"))
                {
                    stageMonitorResultsByLoop["Sensor"] = new List<Dictionary<string, List<BootMonitorResult>>>();
                }
                stageMonitorResultsByLoop["Sensor"].Clear();

                // 过滤出Sensor阶段的寄存器，排除resetverd1[10] - 使用 currentRegisters
                var sensorRegisters = currentRegisters
                    .Where(r => r.Category == "Sensor阶段" && !r.LogInfo.Contains("resetverd1"))
                    .ToList();

                // 按LogInfo分组（相同的寄存器名）
                var groupedRegisters = sensorRegisters
                    .GroupBy(r => r.LogInfo)
                    .ToList();

                for (int i = 0; i < loopCount; i++)
                {
                    // 检查取消请求
                    if (cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        AddLog("Sensor监控被取消");
                        cancellationTokenSource.Token.ThrowIfCancellationRequested();
                    }

                    AddLog($"Sensor监控第 {i + 1} 轮开始");

                    // 为当前循环创建新的结果字典
                    var currentLoopResults = new Dictionary<string, List<BootMonitorResult>>();

                    foreach (var registerGroup in groupedRegisters)
                    {
                        // 修改Process方法，传入当前循环的结果字典
                        ProcessSensorRegisterGroupForLoop(registerGroup.Key, registerGroup.ToList(), currentLoopResults, i);
                    }

                    // 将当前循环的结果添加到总结果中
                    stageMonitorResultsByLoop["Sensor"].Add(currentLoopResults);

                    // 等待间隔时间
                    if (i < loopCount - 1)
                    {
                        for (int waitTime = 0; waitTime < interval; waitTime += 100)
                        {
                            if (cancellationTokenSource.Token.IsCancellationRequested)
                            {
                                AddLog("Sensor监控被取消");
                                cancellationTokenSource.Token.ThrowIfCancellationRequested();
                            }
                            System.Threading.Thread.Sleep(Math.Min(100, interval - waitTime));
                        }
                    }

                    AddLog($"Sensor监控第 {i + 1} 轮完成");
                }

                AddLog($"Sensor监控完成，共 {loopCount} 轮数据");
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                AddLog($"Sensor监控执行出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 处理Boot阶段寄存器组 - 支持多循环版本
        /// </summary>
        private void ProcessBootRegisterGroupForLoop(string logInfo, List<RegisterInfo> registers,
            Dictionary<string, List<BootMonitorResult>> currentLoopResults, int loopIndex)
        {
            try
            {
                // 获取组内第一个寄存器（所有相同LogInfo的寄存器共享相同的地址）
                var firstRegister = registers.First();
                string registerAddress = firstRegister.RegisterAddress;

                if (string.IsNullOrEmpty(registerAddress))
                {
                    AddLog($"寄存器 {logInfo} 地址为空，跳过");
                    return;
                }

                // 读取寄存器值
                uint registerValue = 0;
                string combinedHex = "";
                string msg;

                if (registerAddress.Contains('-'))
                {
                    // 处理地址范围
                    string[] addresses = registerAddress.Split('-');
                    if (addresses.Length == 2)
                    {
                        string startStr = addresses[0].Trim().Replace("0x", "");
                        string endStr = addresses[1].Trim().Replace("0x", "");

                        if (uint.TryParse(startStr, NumberStyles.HexNumber, null, out uint startAddress) &&
                            uint.TryParse(endStr, NumberStyles.HexNumber, null, out uint endAddress))
                        {
                            StringBuilder hexBuilder = new StringBuilder();
                            for (uint addr = startAddress; addr <= endAddress; addr++)
                            {
                                var readData = PageActions.ReadRegister(addr, out msg, 1);
                                if (readData != null && readData.Count > 0)
                                {
                                    registerValue |= (uint)(readData[0] << (int)((addr - startAddress) * 8));
                                    hexBuilder.Insert(0, $"{readData[0]:X2}"); // 小端序
                                }
                            }
                            combinedHex = hexBuilder.ToString();
                        }
                    }
                }
                else
                {
                    // 处理单个地址
                    string cleanAddress = registerAddress.Trim().Replace("0x", "");
                    if (uint.TryParse(cleanAddress, NumberStyles.HexNumber, null, out uint addrValue))
                    {
                        // 根据位宽确定读取的字节数
                        int byteCount = (firstRegister.BitWidth + 7) / 8;
                        var readData = PageActions.ReadRegister(addrValue, out msg, byteCount);

                        if (readData != null && readData.Count > 0)
                        {
                            StringBuilder hexBuilder = new StringBuilder();
                            for (int j = 0; j < readData.Count; j++)
                            {
                                registerValue |= (uint)(readData[j] << (j * 8));
                                hexBuilder.Insert(0, $"{readData[j]:X2}"); // 小端序
                            }
                            combinedHex = hexBuilder.ToString();
                        }
                    }
                }

                // 处理整个寄存器组的所有字段，收集所有错误
                List<(string Error, string LogInfo)> allErrors = new List<(string Error, string LogInfo)>();
                bool hasError = false;

                foreach (var register in registers)
                {
                    var fieldErrors = ProcessRegisterField("Boot", logInfo, register, registerValue, registerAddress);
                    if (fieldErrors.Count > 0)
                    {
                        hasError = true;
                        allErrors.AddRange(fieldErrors);
                    }
                }

                // 对错误列表进行去重
                allErrors = allErrors.Distinct().ToList();

                // 初始化当前logInfo的结果列表
                if (!currentLoopResults.ContainsKey(logInfo))
                {
                    currentLoopResults[logInfo] = new List<BootMonitorResult>();
                }

                // 创建新的结果（每个循环都创建新的结果对象）
                var monitorResult = new BootMonitorResult
                {
                    Value = "0x" + combinedHex,
                    Errors = hasError ? allErrors.Select(e => e.Error).ToList() : new List<string>(),
                    Timestamp = DateTime.Now,
                    RegisterAddress = registerAddress,
                    SortAddress = firstRegister.SortAddress,
                    HasError = hasError,
                    LoopIndex = loopIndex + 1  // 添加循环索引，从1开始
                };

                currentLoopResults[logInfo].Add(monitorResult);

            }
            catch (Exception ex)
            {
                AddLog($"处理寄存器组 {logInfo} 时出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 处理出图阶段寄存器组 - 支持多循环版本
        /// </summary>
        private void ProcessStreamRegisterGroupForLoop(string logInfo, List<RegisterInfo> registers,
            Dictionary<string, List<BootMonitorResult>> currentLoopResults, int loopIndex)
        {
            try
            {
                // 获取组内第一个寄存器（所有相同LogInfo的寄存器共享相同的地址）
                var firstRegister = registers.First();
                string registerAddress = firstRegister.RegisterAddress;

                if (string.IsNullOrEmpty(registerAddress))
                {
                    AddLog($"寄存器 {logInfo} 地址为空，跳过");
                    return;
                }

                // 读取寄存器值
                uint registerValue = 0;
                string combinedHex = "";
                string msg;

                if (registerAddress.Contains('-'))
                {
                    // 处理地址范围
                    string[] addresses = registerAddress.Split('-');
                    if (addresses.Length == 2)
                    {
                        string startStr = addresses[0].Trim().Replace("0x", "");
                        string endStr = addresses[1].Trim().Replace("0x", "");

                        if (uint.TryParse(startStr, NumberStyles.HexNumber, null, out uint startAddress) &&
                            uint.TryParse(endStr, NumberStyles.HexNumber, null, out uint endAddress))
                        {
                            StringBuilder hexBuilder = new StringBuilder();
                            for (uint addr = startAddress; addr <= endAddress; addr++)
                            {
                                var readData = PageActions.ReadRegister(addr, out msg, 1);
                                if (readData != null && readData.Count > 0)
                                {
                                    registerValue |= (uint)(readData[0] << (int)((addr - startAddress) * 8));
                                    hexBuilder.Insert(0, $"{readData[0]:X2}"); // 小端序
                                }
                            }
                            combinedHex = hexBuilder.ToString();
                        }
                    }
                }
                else
                {
                    // 处理单个地址
                    string cleanAddress = registerAddress.Trim().Replace("0x", "");
                    if (uint.TryParse(cleanAddress, NumberStyles.HexNumber, null, out uint addrValue))
                    {
                        // 根据位宽确定读取的字节数
                        int byteCount = (firstRegister.BitWidth + 7) / 8;
                        var readData = PageActions.ReadRegister(addrValue, out msg, byteCount);

                        if (readData != null && readData.Count > 0)
                        {
                            StringBuilder hexBuilder = new StringBuilder();
                            for (int j = 0; j < readData.Count; j++)
                            {
                                registerValue |= (uint)(readData[j] << (j * 8));
                                hexBuilder.Insert(0, $"{readData[j]:X2}"); // 小端序
                            }
                            combinedHex = hexBuilder.ToString();
                        }
                    }
                }

                // 处理整个寄存器组的所有字段，收集所有错误
                List<(string Error, string LogInfo)> allErrors = new List<(string Error, string LogInfo)>();
                bool hasError = false;

                foreach (var register in registers)
                {
                    var fieldErrors = ProcessRegisterField("Stream", logInfo, register, registerValue, registerAddress);
                    if (fieldErrors.Count > 0)
                    {
                        hasError = true;
                        allErrors.AddRange(fieldErrors);
                    }
                }

                // 对错误列表进行去重
                allErrors = allErrors.Distinct().ToList();

                // 初始化当前logInfo的结果列表
                if (!currentLoopResults.ContainsKey(logInfo))
                {
                    currentLoopResults[logInfo] = new List<BootMonitorResult>();
                }

                // 创建新的结果（每个循环都创建新的结果对象）
                var monitorResult = new BootMonitorResult
                {
                    Value = "0x" + combinedHex,
                    Errors = hasError ? allErrors.Select(e => e.Error).ToList() : new List<string>(),
                    Timestamp = DateTime.Now,
                    RegisterAddress = registerAddress,
                    SortAddress = firstRegister.SortAddress,
                    HasError = hasError,
                    LoopIndex = loopIndex + 1  // 添加循环索引，从1开始
                };

                currentLoopResults[logInfo].Add(monitorResult);

            }
            catch (Exception ex)
            {
                AddLog($"处理寄存器组 {logInfo} 时出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 处理Sensor阶段寄存器组 - 支持多循环版本
        /// </summary>
        private void ProcessSensorRegisterGroupForLoop(string logInfo, List<RegisterInfo> registers,
            Dictionary<string, List<BootMonitorResult>> currentLoopResults, int loopIndex)
        {
            try
            {
                // 获取组内第一个寄存器（所有相同LogInfo的寄存器共享相同的地址）
                var firstRegister = registers.First();
                string registerAddress = firstRegister.RegisterAddress;

                if (string.IsNullOrEmpty(registerAddress))
                {
                    AddLog($"寄存器 {logInfo} 地址为空，跳过");
                    return;
                }

                // 读取寄存器值
                uint registerValue = 0;
                string combinedHex = "";
                string msg;

                if (registerAddress.Contains('-'))
                {
                    // 处理地址范围
                    string[] addresses = registerAddress.Split('-');
                    if (addresses.Length == 2)
                    {
                        string startStr = addresses[0].Trim().Replace("0x", "");
                        string endStr = addresses[1].Trim().Replace("0x", "");

                        if (uint.TryParse(startStr, NumberStyles.HexNumber, null, out uint startAddress) &&
                            uint.TryParse(endStr, NumberStyles.HexNumber, null, out uint endAddress))
                        {
                            StringBuilder hexBuilder = new StringBuilder();
                            for (uint addr = startAddress; addr <= endAddress; addr++)
                            {
                                var readData = PageActions.ReadRegister(addr, out msg, 1);
                                if (readData != null && readData.Count > 0)
                                {
                                    registerValue |= (uint)(readData[0] << (int)((addr - startAddress) * 8));
                                    hexBuilder.Insert(0, $"{readData[0]:X2}"); // 小端序
                                }
                            }
                            combinedHex = hexBuilder.ToString();
                        }
                    }
                }
                else
                {
                    // 处理单个地址
                    string cleanAddress = registerAddress.Trim().Replace("0x", "");
                    if (uint.TryParse(cleanAddress, NumberStyles.HexNumber, null, out uint addrValue))
                    {
                        // 根据位宽确定读取的字节数
                        int byteCount = (firstRegister.BitWidth + 7) / 8;
                        var readData = PageActions.ReadRegister(addrValue, out msg, byteCount);

                        if (readData != null && readData.Count > 0)
                        {
                            StringBuilder hexBuilder = new StringBuilder();
                            for (int j = 0; j < readData.Count; j++)
                            {
                                registerValue |= (uint)(readData[j] << (j * 8));
                                hexBuilder.Insert(0, $"{readData[j]:X2}"); // 小端序
                            }
                            combinedHex = hexBuilder.ToString();
                        }
                    }
                }

                // 处理整个寄存器组的所有字段，收集所有错误
                List<(string Error, string LogInfo)> allErrors = new List<(string Error, string LogInfo)>();
                bool hasError = false;

                foreach (var register in registers)
                {
                    var fieldErrors = ProcessRegisterField("Sensor", logInfo, register, registerValue, registerAddress);
                    if (fieldErrors.Count > 0)
                    {
                        hasError = true;
                        allErrors.AddRange(fieldErrors);
                    }
                }

                // 对错误列表进行去重
                allErrors = allErrors.Distinct().ToList();

                // 初始化当前logInfo的结果列表
                if (!currentLoopResults.ContainsKey(logInfo))
                {
                    currentLoopResults[logInfo] = new List<BootMonitorResult>();
                }

                // 创建新的结果（每个循环都创建新的结果对象）
                var monitorResult = new BootMonitorResult
                {
                    Value = "0x" + combinedHex,
                    Errors = hasError ? allErrors.Select(e => e.Error).ToList() : new List<string>(),
                    Timestamp = DateTime.Now,
                    RegisterAddress = registerAddress,
                    SortAddress = firstRegister.SortAddress,
                    HasError = hasError,
                    LoopIndex = loopIndex + 1  // 添加循环索引，从1开始
                };

                currentLoopResults[logInfo].Add(monitorResult);

            }
            catch (Exception ex)
            {
                AddLog($"处理寄存器组 {logInfo} 时出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 通用处理寄存器字段 - 返回错误列表
        /// </summary>
        private List<(string Error, string LogInfo)> ProcessRegisterField(string stage, string logInfo, RegisterInfo register, uint registerValue, string registerAddress)
        {
            List<(string Error, string LogInfo)> errors = new List<(string Error, string LogInfo)>();

            // 特殊处理1：如果logInfo包含"Size"或者register.Parameter为空，则不进行报错  不过滤IspSizeState[7:0]
            if ((logInfo.Contains("Size") && logInfo != "IspSizeState[7:0]") || string.IsNullOrEmpty(register.Parameter))
            {
                // 对于Size类型（除了IspSizeState[7:0]）或没有参数定义的寄存器，即使有值也不报错
                AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 信息: {register.Description}");
                return errors;
            }

            // 特殊处理2：IspSizeState[7:0]的特殊验证
            if (logInfo == "IspSizeState[7:0]")
            {
                // 取低8位值
                byte sizeStateValue = (byte)(registerValue & 0xFF);

                // 检查各个位
                bool mipiRxSizeError = (sizeStateValue & 0x01) != 0;  // 位0: MipiRxSize错误
                bool ispInputSizeError = (sizeStateValue & 0x02) != 0; // 位1: IspInputSize错误  
                bool ispOutputSizeError = (sizeStateValue & 0x04) != 0; // 位2: IspOutputSize错误

                if (sizeStateValue == 0)
                {
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 所有Size状态正常");
                }
                else
                {
                    if (mipiRxSizeError)
                    {
                        errors.Add(("[0]isp mipi rx size error", logInfo));
                        errors.Add(($"尺寸错误", "MipiRxSize[31:0]"));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8}");
                    }

                    if (ispInputSizeError)
                    {
                        errors.Add(("[1]isp crc input size error", logInfo));
                        errors.Add(($"尺寸错误", "IspInputSize[31:0]"));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} ");
                    }

                    if (ispOutputSizeError)
                    {
                        
                        errors.Add(("[2]isp output size error", logInfo));
                        errors.Add(($"尺寸错误", "IspOutputSize[31:0]"));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} ");
                    }

                    // 检查其他位（如果有）
                    if ((sizeStateValue & 0xF8) != 0)
                    {
                        string otherBits = Convert.ToString(sizeStateValue, 2).PadLeft(8, '0');
                        string errorMsg = $"IspSizeState其他位异常: {otherBits}";
                        errors.Add((errorMsg, logInfo));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                    }
                }
                return errors;
            }

            // 特殊处理3：FrontSensorIndex和RearSensorIndex的特殊验证
            if (logInfo == "FrontSensorIndex[7:0]" || logInfo == "RearSensorIndex[7:0]")
            {
                // 取低8位值
                byte sensorValue = (byte)(registerValue & 0xFF);

                // 允许的传感器ID值：1, 2, 3, 4
                if (sensorValue >= 1 && sensorValue <= 4)
                {
                    string sensorName = GetSensorName(logInfo, sensorValue);
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 传感器ID: {sensorValue} ({sensorName})");
                }
                else
                {
                    string errorMsg = $"无效的传感器ID: 0x{sensorValue:X} (允许值: 1-4)";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                return errors;
            }

            // 特殊处理4：USBDevicesStatus[7:0] 的状态验证
            if (logInfo == "USBDevicesStatus[7:0]")
            {
                // 取低8位值
                byte usbStatusValue = (byte)(registerValue & 0xFF);

                if (usbStatusValue == 3)
                {
                    // 状态3：正常
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - USB设备状态正常: 0x{usbStatusValue:X} ");
                }
                else if (usbStatusValue == 2)
                {
                    // 状态2：需要状态3
                    string errorMsg = $"USB设备状态: 0x{usbStatusValue:X}  -> 需要状态 0x03 (set config after)";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                else if (usbStatusValue == 1)
                {
                    // 状态1：需要状态2或3
                    string errorMsg = $"USB设备状态: 0x{usbStatusValue:X}  -> 需要状态 0x02 (set address after) 或 0x03 (set config after)";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                else
                {
                    // 其他状态值
                    string errorMsg = $"USB设备状态异常: 0x{usbStatusValue:X} (允许值: 0x01, 0x02, 0x03)";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                return errors;
            }

            // 特殊处理5：FrameEofCnt[7:0] - 值大于0报错
            if (logInfo == "FrameEofCnt[7:0]")
            {
                byte frameEofValue = (byte)(registerValue & 0xFF);
                if (frameEofValue > 0)
                {
                    string errorMsg = $"存在 {frameEofValue} 帧错误帧，idc开流后，usb开流前出现错误帧";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                else
                {
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 错误帧数为0，正常");
                }
                return errors;
            }

            // 特殊处理6：StreamLoadFlag[7:0] - 等于0x2报错USB开流超时
            if (logInfo == "StreamLoadFlag[7:0]")
            {
                byte streamLoadValue = (byte)(registerValue & 0xFF);

                switch (streamLoadValue)
                {
                    case 0x00:
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - StreamInit: 开流初始化");
                        break;
                    case 0x01:
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - StreamOnRun: USB开流");
                        break;
                    case 0x02:
                        string errorMsg = "USB开流超时";
                        errors.Add((errorMsg, logInfo));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                        break;
                    case 0x03:
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - StreamLoadFinish: 加载拍照setting成功");
                        break;
                    default:
                        string unknownMsg = $"未知的StreamLoadFlag状态: 0x{streamLoadValue:X2}";
                        errors.Add((unknownMsg, logInfo));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {unknownMsg}");
                        break;
                }
                return errors;
            }
            // 特殊处理7：IsStreamOn[7:0] - 值不等于报错
            if (logInfo == "IsStreamOn[7:0]")
            {
                byte streamOnValue = (byte)(registerValue & 0xFF);

                if (streamOnValue != 0x1)
                {
                    string errorMsg = $"流未正确开启，当前状态: 0x{streamOnValue:X2} (期望: 0x01)";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                else
                {
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 流已正确开启");
                }
                return errors;
            }

            // 特殊处理8：_OverTime - 值不等于报错
            if (logInfo.Contains("OverTime"))
            {
                if (registerValue > 0x0)
                {
                    string errorMsg = $"{logInfo} 检测到{register.Parameter}错误，错误码: 0x{registerValue:X} ";
                    errors.Add((errorMsg, logInfo));
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - {errorMsg}");
                }
                else
                {
                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 流已正确开启");
                }
                return errors;
            }

            // 检查Parameter字段是否包含位定义
            if (!string.IsNullOrEmpty(register.Parameter) && register.Parameter.StartsWith("[") && register.Parameter.Contains("]"))
            {
                // 提取位范围
                int bitStart = register.Parameter.IndexOf('[') + 1;
                int bitEnd = register.Parameter.IndexOf(']');
                string bitStr = register.Parameter.Substring(bitStart, bitEnd - bitStart);

                // 处理单个位
                if (int.TryParse(bitStr, out int bitIndex))
                {
                    if (bitIndex >= 0 && bitIndex < register.BitWidth)
                    {
                        bool bitSet = (registerValue & (1u << bitIndex)) != 0;
                        if (bitSet)
                        {
                            string errorMsg = $"{register.Parameter}-{register.Description}";
                            errors.Add((errorMsg, logInfo));
                            AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 位 [{bitIndex}] 置1: {register.Description}");
                        }
                    }
                }
                // 处理位范围 [high:low]
                else if (bitStr.Contains(":"))
                {
                    string[] rangeParts = bitStr.Split(':');
                    if (rangeParts.Length == 2 &&
                        int.TryParse(rangeParts[0], out int highBit) &&
                        int.TryParse(rangeParts[1], out int lowBit))
                    {
                        if (highBit >= lowBit && lowBit >= 0 && highBit < register.BitWidth)
                        {
                            int bitWidth = highBit - lowBit + 1;
                            uint mask = (1u << bitWidth) - 1;
                            uint fieldValue = (registerValue >> lowBit) & mask;

                            // 对于非零值的字段记录信息
                            if (fieldValue != 0)
                            {
                                // 特殊处理5：判断是否需要报错
                                if (ShouldReportError(register.Parameter))
                                {
                                    string errorMsg = $"{register.Parameter}-{register.Description} (值: 0x{fieldValue:X})";
                                    errors.Add((errorMsg, logInfo));
                                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 位 [{highBit}:{lowBit}] = 0x{fieldValue:X}: {register.Description}");
                                }
                                else
                                {
                                    AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X8} - 位 [{highBit}:{lowBit}] = 0x{fieldValue:X} (正常状态): {register.Description}");
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                // 对于没有位定义的寄存器，检查整个寄存器值
                if (registerValue != 0)
                {
                    // 特殊处理5：判断是否需要报错
                    if (ShouldReportError(register.Parameter))
                    {
                        string errorMsg = $"{register.Parameter}-{register.Description} (寄存器值: 0x{registerValue:X})";
                        errors.Add((errorMsg, logInfo));
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X}: {register.Description}");
                    }
                    else
                    {
                        AddLog($"{stage}阶段 - {logInfo} (0x{registerAddress}) = 0x{registerValue:X} (正常状态): {register.Description}");
                    }
                }
            }

            return errors;
        }



        /// <summary>
        /// 判断是否需要报错（包含"_state"或"_err"或"_full"或"error"的寄存器需要报错）
        /// </summary>
        private bool ShouldReportError( string parameter)
        {
            // 检查logInfo或description是否包含需要报错的关键字
            string combinedText = (parameter).ToLower();

            return combinedText.Contains("error") ||
          combinedText.Contains("_state") ||
          combinedText.Contains("_err") ||
          combinedText.Contains("_full") ||
          combinedText.Contains("state") ||
          combinedText.Contains("异常") ||
          combinedText.Contains("失败") ||
          combinedText.Contains("错误");
        }

        /// <summary>
        /// 获取传感器名称
        /// </summary>
        private string GetSensorName(string logInfo, byte sensorValue)
        {
            if (logInfo == "FrontSensorIndex[7:0]")
            {
                switch (sensorValue)
                {
                    case 3: return "SC820CS";
                    case 4: return "GC08A8";
                    default: return "未知前摄";
                }
            }
            else if (logInfo == "RearSensorIndex[7:0]")
            {
                switch (sensorValue)
                {
                    case 2: return "SC1320";
                    case 1: return "GC13A0";
                    default: return "未知后摄";
                }
            }
            return "未知传感器";
        }



        private void ExportALLExcel_Click(object sender, RoutedEventArgs e)
        {
            // 检查是否有监控数据（多循环版本）
            bool hasBootData = stageMonitorResultsByLoop.ContainsKey("Boot") && stageMonitorResultsByLoop["Boot"].Count > 0;
            bool hasStreamData = stageMonitorResultsByLoop.ContainsKey("Stream") && stageMonitorResultsByLoop["Stream"].Count > 0;
            bool hasSensorData = stageMonitorResultsByLoop.ContainsKey("Sensor") && stageMonitorResultsByLoop["Sensor"].Count > 0;

            if (!hasBootData && !hasStreamData && !hasSensorData)
            {
                MessageBox.Show("没有监控数据可导出", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "Excel文件 (*.xlsx)|*.xlsx|Excel 97-2003文件 (*.xls)|*.xls|所有文件 (*.*)|*.*",
                FileName = $"维测信息分析结果_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    // 根据文件扩展名确定使用 xlsx 还是 xls 格式
                    IWorkbook workbook;
                    if (saveFileDialog.FileName.ToLower().EndsWith(".xls"))
                    {
                        workbook = new HSSFWorkbook(); // xls 格式
                    }
                    else
                    {
                        workbook = new XSSFWorkbook(); // xlsx 格式
                    }

                    // 创建样式
                    ICellStyle headerStyle = CreateHeaderStyle(workbook);
                    ICellStyle errorStyle = CreateErrorStyle(workbook);
                    ICellStyle normalStyle = CreateNormalStyle(workbook);
                    ICellStyle successStyle = CreateSuccessStyle(workbook);
                    ICellStyle titleStyle = CreateTitleStyle(workbook);
                    ICellStyle loopHeaderStyle = CreateLoopHeaderStyle(workbook);
                    ICellStyle stageHeaderStyle = CreateStageHeaderStyle(workbook);

                    // 创建工作表 - 所有数据放在一个工作表中
                    ISheet sheet = workbook.CreateSheet("维测监控汇总");

                    // 计算所有阶段的最大错误数量
                    int maxErrorCount = CalculateAllStagesMaxErrorCount();

                    // 设置标题行（添加地址列）
                    SetExcelHeadersWithAddress(sheet, headerStyle, maxErrorCount);

                    int currentRow = 1; // 从第2行开始（索引1）

                    // 确定循环次数（取三个阶段中的最大循环次数）
                    int maxLoopCount = GetMaxLoopCount();

                    // 按循环次数导出数据（Boot+Stream+Sensor为一组）
                    for (int loopIndex = 0; loopIndex < maxLoopCount; loopIndex++)
                    {
                        currentRow = ExportLoopDataToSheet(sheet, loopIndex,
                            normalStyle, errorStyle, successStyle, titleStyle,
                            loopHeaderStyle, stageHeaderStyle, maxErrorCount, currentRow);

                        // 循环之间空一行（除非是最后一个循环）
                        if (loopIndex < maxLoopCount - 1)
                        {
                            currentRow++;
                        }
                    }

                    // 自动调整列宽
                    AutoSizeColumns(sheet, 4 + maxErrorCount + 1); // 列数 = 维测字段 + 地址 + 字段内容 + 错误列数 + 时间戳

                    // 保存Excel文件
                    using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
                    {
                        workbook.Write(fs);
                    }

                    AddLog($"所有阶段监控数据已导出到: {saveFileDialog.FileName}");

                    // 生成对应的文本文件
                    GenerateTextReport(saveFileDialog.FileName);

                    // 询问用户是否打开文件路径
                    var result = MessageBox.Show($"Excel文件已成功导出！\n\n文件路径：{saveFileDialog.FileName}\n\n是否打开文件所在文件夹？",
                        "导出成功",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        try
                        {
                            // 直接打开Excel文件
                            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                            {
                                FileName = saveFileDialog.FileName,
                                UseShellExecute = true
                            });
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"打开Excel文件失败: {ex.Message}", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出Excel失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    AddLog($"导出Excel失败: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 导出单个循环的数据到工作表（包含Boot+Stream+Sensor三个阶段）
        /// </summary>
        private int ExportLoopDataToSheet(ISheet sheet, int loopIndex,
            ICellStyle normalStyle, ICellStyle errorStyle, ICellStyle successStyle,
            ICellStyle titleStyle, ICellStyle loopHeaderStyle, ICellStyle stageHeaderStyle,
            int maxErrorCount, int startRow)
        {
            int currentRow = startRow;
            int timestampColumn = 3 + maxErrorCount;

            // 添加循环标题行
            IRow loopTitleRow = sheet.CreateRow(currentRow);
            CreateCell(loopTitleRow, 0, $"第 {loopIndex + 1} 轮循环", loopHeaderStyle);
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(currentRow, currentRow, 0, timestampColumn));
            currentRow++;

            // 导出Boot阶段数据
            if (stageMonitorResultsByLoop.ContainsKey("Boot") && loopIndex < stageMonitorResultsByLoop["Boot"].Count)
            {
                currentRow = ExportSingleStageDataToSheet(sheet, "Boot阶段",
                    stageMonitorResultsByLoop["Boot"][loopIndex],
                    normalStyle, errorStyle, successStyle, stageHeaderStyle,
                    maxErrorCount, currentRow);
            }

            // 导出出图阶段数据
            if (stageMonitorResultsByLoop.ContainsKey("Stream") && loopIndex < stageMonitorResultsByLoop["Stream"].Count)
            {
                currentRow = ExportSingleStageDataToSheet(sheet, "出图阶段",
                    stageMonitorResultsByLoop["Stream"][loopIndex],
                    normalStyle, errorStyle, successStyle, stageHeaderStyle,
                    maxErrorCount, currentRow);
            }

            // 导出Sensor阶段数据
            if (stageMonitorResultsByLoop.ContainsKey("Sensor") && loopIndex < stageMonitorResultsByLoop["Sensor"].Count)
            {
                currentRow = ExportSingleStageDataToSheet(sheet, "Sensor阶段",
                    stageMonitorResultsByLoop["Sensor"][loopIndex],
                    normalStyle, errorStyle, successStyle, stageHeaderStyle,
                    maxErrorCount, currentRow);
            }

            return currentRow;
        }
        /// <summary>
        /// 导出单个阶段的数据到工作表
        /// </summary>
        private int ExportSingleStageDataToSheet(ISheet sheet, string stageName,
            Dictionary<string, List<BootMonitorResult>> stageData,
            ICellStyle normalStyle, ICellStyle errorStyle, ICellStyle successStyle,
            ICellStyle stageHeaderStyle, int maxErrorCount, int startRow)
        {
            int currentRow = startRow;
            int timestampColumn = 3 + maxErrorCount;

            // 添加阶段标题行
            IRow stageTitleRow = sheet.CreateRow(currentRow);
            CreateCell(stageTitleRow, 0, stageName, stageHeaderStyle);
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(currentRow, currentRow, 0, timestampColumn));
            currentRow++;

            // 过滤掉 resetverd1[10] 相关的数据，并按照 SortAddress 排序
            var filteredResults = stageData
                .Where(kvp => !kvp.Key.Contains("resetverd1"))
                .Select(kvp => new
                {
                    Key = kvp.Key,
                    Result = kvp.Value.FirstOrDefault() // 每个寄存器在每个循环中应该只有一个结果
        })
                .Where(x => x.Result != null)
                .OrderBy(x => x.Result.SortAddress)
                .ToList();

            // 填充当前阶段的数据
            foreach (var item in filteredResults)
            {
                var result = item.Result;
                IRow dataRow = sheet.CreateRow(currentRow);

                // 维测字段
                CreateCell(dataRow, 0, item.Key, normalStyle);

                // 地址
                CreateCell(dataRow, 1, result.RegisterAddress, normalStyle);

                // 字段内容
                CreateCell(dataRow, 2, result.Value, normalStyle);

                // 时间戳
                CreateCell(dataRow, timestampColumn, result.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"), normalStyle);

                // 填充错误信息或状态
                if (result.HasError && result.Errors.Count > 0)
                {
                    // 有错误的情况
                    for (int i = 0; i < result.Errors.Count && i < maxErrorCount; i++)
                    {
                        CreateCell(dataRow, 3 + i, result.Errors[i], errorStyle);
                    }
                }
                else if (result.HasError)
                {
                    // 有错误标识但没有具体错误信息
                    CreateCell(dataRow, 3, "检测到错误", errorStyle);
                }
                else
                {
                    // 没有错误的情况
                    CreateCell(dataRow, 3, "正常", successStyle);
                }

                currentRow++;
            }

            // 阶段之间空一行
            currentRow++;

            return currentRow;
        }
        /// <summary>
        /// 创建阶段标题样式
        /// </summary>
        private ICellStyle CreateStageHeaderStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 11;
            //font.Boldweight = (short)FontBoldWeight.Bold; // 设置加粗
            font.Color = IndexedColors.Black.Index; // 设置成黑色
            style.SetFont(font);

            // 设置成浅灰色背景
            style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
            style.FillPattern = FillPattern.SolidForeground;
            //style.Alignment = Left; // 取消注释，保持左对齐

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            return style;
        }

        /// <summary>
        /// 获取最大循环次数
        /// </summary>
        private int GetMaxLoopCount()
        {
            int maxLoopCount = 0;

            if (stageMonitorResultsByLoop.ContainsKey("Boot") && stageMonitorResultsByLoop["Boot"].Count > maxLoopCount)
                maxLoopCount = stageMonitorResultsByLoop["Boot"].Count;

            if (stageMonitorResultsByLoop.ContainsKey("Stream") && stageMonitorResultsByLoop["Stream"].Count > maxLoopCount)
                maxLoopCount = stageMonitorResultsByLoop["Stream"].Count;

            if (stageMonitorResultsByLoop.ContainsKey("Sensor") && stageMonitorResultsByLoop["Sensor"].Count > maxLoopCount)
                maxLoopCount = stageMonitorResultsByLoop["Sensor"].Count;

            return maxLoopCount;
        }

        /// <summary>
        /// 创建循环标题样式
        /// </summary>
        private ICellStyle CreateLoopHeaderStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 12;
            //font.Boldweight = (short)FontBoldWeight.Bold;
            font.Color = IndexedColors.DarkBlue.Index;
            style.SetFont(font);

            style.FillForegroundColor = IndexedColors.Yellow.Index;
            style.FillPattern = FillPattern.SolidForeground;
            //style.Alignment = HorizontalAlignment.Left;

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            return style;
        }
        /// <summary>
        /// 创建标题行样式
        /// </summary>
        private ICellStyle CreateHeaderStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.IsBold = true;
            font.FontName = "微软雅黑";
            style.SetFont(font);

            // 设置背景色 - 浅蓝色
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightBlue.Index;
            style.FillPattern = FillPattern.SolidForeground;

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            // 设置居中对齐
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;

            return style;
        }

        /// <summary>
        /// 创建错误文本样式
        /// </summary>
        private ICellStyle CreateErrorStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index;
            font.FontName = "微软雅黑";
            style.SetFont(font);

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            return style;
        }

        /// <summary>
        /// 创建成功文本样式
        /// </summary>
        private ICellStyle CreateSuccessStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index;
            font.FontName = "微软雅黑";
            style.SetFont(font);

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            return style;
        }

        /// <summary>
        /// 创建普通文本样式
        /// </summary>
        private ICellStyle CreateNormalStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.FontName = "微软雅黑";
            style.SetFont(font);

            // 设置边框
            style.BorderBottom = BorderStyle.Thin;
            style.BorderLeft = BorderStyle.Thin;
            style.BorderRight = BorderStyle.Thin;
            style.BorderTop = BorderStyle.Thin;

            return style;
        }

        /// <summary>
        /// 设置Excel表头
        /// </summary>
        private void SetExcelHeaders(ISheet sheet, ICellStyle headerStyle, int maxErrorCount)
        {
            IRow headerRow = sheet.CreateRow(0);

            // 设置标题行
            CreateCell(headerRow, 0, "维测字段", headerStyle);
            CreateCell(headerRow, 1, "字段内容", headerStyle);

            // 动态生成错误列
            for (int i = 0; i < maxErrorCount; i++)
            {
                CreateCell(headerRow, 2 + i, $"错误{i + 1}", headerStyle);
            }

            // 时间戳列的位置 = 2 + maxErrorCount
            int timestampColumn = 2 + maxErrorCount;
            CreateCell(headerRow, timestampColumn, "时间戳", headerStyle);
        }

        /// <summary>
        /// 创建单元格
        /// </summary>
        private void CreateCell(IRow row, int columnIndex, string value, ICellStyle style)
        {
            ICell cell = row.CreateCell(columnIndex);
            cell.SetCellValue(value);
            if (style != null)
            {
                cell.CellStyle = style;
            }
        }




        /// <summary>
        /// 自动调整列宽
        /// </summary>
        private void AutoSizeColumns(ISheet sheet, int columnCount)
        {
            for (int i = 0; i < columnCount; i++)
            {
                sheet.AutoSizeColumn(i);

                // 设置最小列宽
                if (sheet.GetColumnWidth(i) < 3000) // 大约相当于15个字符宽度
                {
                    sheet.SetColumnWidth(i, 3000);
                }
            }
        }



        /// <summary>
        /// 创建标题样式
        /// </summary>
        private ICellStyle CreateTitleStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.IsBold = true;
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 14;
            style.SetFont(font);

            // 设置背景色 - 浅灰色
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
            style.FillPattern = FillPattern.SolidForeground;

            // 设置居中对齐
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;

            return style;
        }

        /// <summary>
        /// 计算所有阶段的最大错误数量
        /// </summary>
        private int CalculateAllStagesMaxErrorCount()
        {
            int maxErrorCount = 0;

            // 检查Boot阶段
            foreach (var kvp in stageMonitorResults["Boot"])
            {
                var lastResult = kvp.Value.LastOrDefault();
                if (lastResult != null && lastResult.Errors.Count > maxErrorCount)
                {
                    maxErrorCount = lastResult.Errors.Count;
                }
            }

            // 检查出图阶段
            foreach (var kvp in stageMonitorResults["Stream"])
            {
                var lastResult = kvp.Value.LastOrDefault();
                if (lastResult != null && lastResult.Errors.Count > maxErrorCount)
                {
                    maxErrorCount = lastResult.Errors.Count;
                }
            }

            // 检查Sensor阶段
            foreach (var kvp in stageMonitorResults["Sensor"])
            {
                var lastResult = kvp.Value.LastOrDefault();
                if (lastResult != null && lastResult.Errors.Count > maxErrorCount)
                {
                    maxErrorCount = lastResult.Errors.Count;
                }
            }

            // 如果没有错误，至少保留一列用于显示"正常"信息
            return Math.Max(maxErrorCount, 1);
        }

        /// <summary>
        /// 设置Excel表头（包含地址列）
        /// </summary>
        private void SetExcelHeadersWithAddress(ISheet sheet, ICellStyle headerStyle, int maxErrorCount)
        {
            IRow headerRow = sheet.CreateRow(0);

            // 设置标题行
            CreateCell(headerRow, 0, "维测字段", headerStyle);
            CreateCell(headerRow, 1, "地址", headerStyle);
            CreateCell(headerRow, 2, "字段内容", headerStyle);

            // 动态生成错误列
            for (int i = 0; i < maxErrorCount; i++)
            {
                CreateCell(headerRow, 3 + i, $"错误{i + 1}", headerStyle);
            }

            // 时间戳列的位置 = 3 + maxErrorCount
            int timestampColumn = 3 + maxErrorCount;
            CreateCell(headerRow, timestampColumn, "时间戳", headerStyle);
        }


        /// <summary>
        /// 将阶段数据填充到工作表的指定位置
        /// </summary>
        private int FillStageDataToSheet(ISheet sheet, string stageName, Dictionary<string, List<BootMonitorResult>> monitorResults,
            ICellStyle normalStyle, ICellStyle errorStyle, ICellStyle successStyle, ICellStyle titleStyle, int maxErrorCount, int startRow)
        {
            int timestampColumn = 3 + maxErrorCount;
            int currentRow = startRow;

            // 添加阶段标题行
            IRow titleRow = sheet.CreateRow(currentRow);
            CreateCell(titleRow, 0, stageName, titleStyle);
            sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(currentRow, currentRow, 0, timestampColumn));
            currentRow++;

            // 过滤掉 resetverd1[10] 相关的数据，并按照 SortAddress 排序
            var filteredResults = monitorResults
                .Where(kvp => !kvp.Key.Contains("resetverd1"))
                .Select(kvp => new
                {
                    Key = kvp.Key,
                    LastResult = kvp.Value.LastOrDefault()
                })
                .Where(x => x.LastResult != null)
                .OrderBy(x => x.LastResult.SortAddress)  // 添加排序
                .ToList();

            foreach (var item in filteredResults)
            {
                var lastResult = item.LastResult;
                IRow dataRow = sheet.CreateRow(currentRow);

                // 维测字段
                CreateCell(dataRow, 0, item.Key, normalStyle);

                // 地址
                CreateCell(dataRow, 1, lastResult.RegisterAddress, normalStyle);

                // 字段内容
                CreateCell(dataRow, 2, lastResult.Value, normalStyle);

                // 时间戳
                CreateCell(dataRow, timestampColumn, lastResult.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"), normalStyle);

                // 填充错误信息或状态
                if (lastResult.HasError && lastResult.Errors.Count > 0)
                {
                    // 有错误的情况
                    for (int i = 0; i < lastResult.Errors.Count && i < maxErrorCount; i++)
                    {
                        CreateCell(dataRow, 3 + i, lastResult.Errors[i], errorStyle);
                    }
                }
                else if (lastResult.HasError)
                {
                    // 有错误标识但没有具体错误信息
                    CreateCell(dataRow, 3, "检测到错误", errorStyle);
                }
                else
                {
                    // 没有错误的情况
                    CreateCell(dataRow, 3, "正常", successStyle);
                }

                currentRow++;
            }

            return currentRow;
        }

        /// <summary>
        /// 生成文本报告（按循环分组）
        /// </summary>
        private void GenerateTextReport(string excelFilePath)
        {
            try
            {
                // 生成文本文件路径（与Excel文件同路径，扩展名为.txt）
                string txtFilePath = Path.Combine(
                    Path.GetDirectoryName(excelFilePath),
                    Path.GetFileNameWithoutExtension(excelFilePath) + ".txt");

                using (StreamWriter writer = new StreamWriter(txtFilePath, false, Encoding.UTF8))
                {
                    // 写入文件头
                    writer.WriteLine("====================================");
                    writer.WriteLine("       维测监控汇总报告");
                    writer.WriteLine("====================================");
                    writer.WriteLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                    writer.WriteLine();

                    // 确定循环次数
                    int maxLoopCount = GetMaxLoopCount();

                    // 按循环次数导出数据
                    for (int loopIndex = 0; loopIndex < maxLoopCount; loopIndex++)
                    {
                        WriteLoopDataToText(writer, loopIndex);
                        writer.WriteLine(); // 循环间空行
                    }
                }

                AddLog($"文本报告已生成: {txtFilePath}");
            }
            catch (Exception ex)
            {
                AddLog($"生成文本报告失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 将单个循环的数据写入文本（包含Boot+Stream+Sensor三个阶段）
        /// </summary>
        private void WriteLoopDataToText(StreamWriter writer, int loopIndex)
        {
            writer.WriteLine($"第 {loopIndex + 1} 轮循环");
            writer.WriteLine(new string('=', 50));

            // 写入Boot阶段数据
            if (stageMonitorResultsByLoop.ContainsKey("Boot") && loopIndex < stageMonitorResultsByLoop["Boot"].Count)
            {
                WriteSingleStageToText(writer, "Boot阶段", stageMonitorResultsByLoop["Boot"][loopIndex]);
            }

            // 写入出图阶段数据
            if (stageMonitorResultsByLoop.ContainsKey("Stream") && loopIndex < stageMonitorResultsByLoop["Stream"].Count)
            {
                WriteSingleStageToText(writer, "出图阶段", stageMonitorResultsByLoop["Stream"][loopIndex]);
            }

            // 写入Sensor阶段数据
            if (stageMonitorResultsByLoop.ContainsKey("Sensor") && loopIndex < stageMonitorResultsByLoop["Sensor"].Count)
            {
                WriteSingleStageToText(writer, "Sensor阶段", stageMonitorResultsByLoop["Sensor"][loopIndex]);
            }
        }
        /// <summary>
        /// 将单个阶段的数据写入文本
        /// </summary>
        private void WriteSingleStageToText(StreamWriter writer, string stageName, Dictionary<string, List<BootMonitorResult>> stageData)
        {
            writer.WriteLine($"{stageName}:");
            writer.WriteLine(new string('-', 30));

            // 表头
            writer.WriteLine("寄存器\t\t地址\t\t值\t\t状态");
            writer.WriteLine(new string('-', 80));

            // 按SortAddress排序
            var sortedRegisters = stageData
                .Where(kvp => !kvp.Key.Contains("resetverd1"))
                .OrderBy(kvp => kvp.Value.First().SortAddress)
                .ToList();

            foreach (var kvp in sortedRegisters)
            {
                var result = kvp.Value.FirstOrDefault();
                if (result != null)
                {
                    // 格式化输出，确保对齐
                    string registerName = kvp.Key.PadRight(20);
                    string address = result.RegisterAddress.PadRight(15);
                    string value = result.Value.PadRight(15);
                    string status = result.HasError ? "有错误" : "正常";

                    writer.WriteLine($"{registerName}\t{address}\t{value}\t{status}");
                }
            }
            writer.WriteLine(); // 阶段间空行
        }
        /// <summary>
        /// 将阶段数据写入文本
        /// </summary>
        private void WriteStageToText(StreamWriter writer, string stageName, Dictionary<string, List<BootMonitorResult>> monitorResults)
        {
            writer.WriteLine($"【{stageName}】");
            writer.WriteLine(new string('-', 50));

            // 表头
            writer.WriteLine("寄存器\t\t地址\t\t值\t\t状态");
            writer.WriteLine(new string('-', 80));

            foreach (var kvp in monitorResults)
            {
                var lastResult = kvp.Value.LastOrDefault();
                if (lastResult != null)
                {
                    // 格式化输出，确保对齐
                    string registerName = kvp.Key.PadRight(20);
                    string address = lastResult.RegisterAddress.PadRight(15);
                    string value = lastResult.Value.PadRight(15);
                    string status = lastResult.HasError ? "有错误" : "正常";

                    writer.WriteLine($"{registerName}\t{address}\t{value}\t{status}");
                }
            }
            writer.WriteLine(); // 阶段间空行
        }




        /// <summary>
        /// 将单个阶段数据导出到工作簿
        /// </summary>
        private void ExportStageToWorkbook(IWorkbook workbook, string sheetName, Dictionary<string, List<BootMonitorResult>> monitorResults,
            ICellStyle headerStyle, ICellStyle normalStyle, ICellStyle errorStyle, ICellStyle successStyle)
        {
            // 计算该阶段的最大错误数量
            int maxErrorCount = CalculateMaxErrorCount(monitorResults);

            // 创建工作表
            ISheet sheet = workbook.CreateSheet(sheetName);

            // 设置标题行
            SetExcelHeaders(sheet, headerStyle, maxErrorCount);

            // 填充数据
            FillStageExcelData(sheet, normalStyle, errorStyle, successStyle, maxErrorCount, monitorResults);

            // 自动调整列宽
            AutoSizeColumns(sheet, 3 + maxErrorCount + 1);
        }
        /// <summary>
        /// 填充单个阶段Excel数据
        /// </summary>
        private void FillStageExcelData(ISheet sheet, ICellStyle normalStyle, ICellStyle errorStyle, ICellStyle successStyle,
            int maxErrorCount, Dictionary<string, List<BootMonitorResult>> monitorResults)
        {
            int timestampColumn = 2 + maxErrorCount;
            int rowIndex = 1;

            foreach (var kvp in monitorResults)
            {
                // 只取最后一次监控结果
                var lastResult = kvp.Value.LastOrDefault();
                if (lastResult != null)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    // 维测字段
                    CreateCell(dataRow, 0, kvp.Key, normalStyle);

                    // 字段内容
                    CreateCell(dataRow, 1, lastResult.Value, normalStyle);

                    // 时间戳
                    CreateCell(dataRow, timestampColumn, lastResult.Timestamp.ToString("yyyy-MM-dd HH:mm:ss"), normalStyle);

                    // 填充错误信息或状态
                    if (lastResult.HasError && lastResult.Errors.Count > 0)
                    {
                        // 有错误的情况
                        for (int i = 0; i < lastResult.Errors.Count && i < maxErrorCount; i++)
                        {
                            CreateCell(dataRow, 2 + i, lastResult.Errors[i], errorStyle);
                        }
                    }
                    else if (lastResult.HasError)
                    {
                        // 有错误标识但没有具体错误信息（理论上不应该出现）
                        CreateCell(dataRow, 2, "检测到错误", errorStyle);
                    }
                    else
                    {
                        // 没有错误的情况
                        CreateCell(dataRow, 2, "正常", successStyle);
                    }

                    rowIndex++;
                }
            }
        }


        /// <summary>
        /// 计算所有监控结果中的最大错误数量
        /// </summary>
        private int CalculateMaxErrorCount(Dictionary<string, List<BootMonitorResult>> monitorResults)
        {
            int maxErrorCount = 0;
            foreach (var kvp in monitorResults)
            {
                var lastResult = kvp.Value.LastOrDefault();
                if (lastResult != null && lastResult.Errors.Count > maxErrorCount)
                {
                    maxErrorCount = lastResult.Errors.Count;
                }
            }

            // 如果没有错误，至少保留一列用于显示"无错误"信息
            return Math.Max(maxErrorCount, 1);
        }
        /// <summary>
        /// 加载后载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string baseAddressText = txtbaseAddress.Text.Trim();
            UpdateBaseAddress(baseAddressText);
        }



        // 全部监控事件
        private async void StartAllMonitoring_Click(object sender, RoutedEventArgs e)
        {


            // 添加设备检查
            if (!CheckDeviceOpened("全部监控"))
            {
                return;
            }

            // 显示带固件版本号的确认对话框
            var confirmDialog = new ExportConfirmDialog();
            confirmDialog.Owner = this; // 设置父窗口

            bool? result = confirmDialog.ShowDialog();
            if (result == true && confirmDialog.ExportConfirmed)
            {


                if (!int.TryParse(txtBootLoopCount.Text, out int bootLoopCount) ||
                    !int.TryParse(txtBootInterval.Text, out int bootInterval) ||
                    !int.TryParse(txtStreamLoopCount.Text, out int streamLoopCount) ||
                    !int.TryParse(txtStreamInterval.Text, out int streamInterval) ||
                    !int.TryParse(txtSensorLoopCount.Text, out int sensorLoopCount) ||
                    !int.TryParse(txtSensorInterval.Text, out int sensorInterval))
                {
                    MessageBox.Show("请输入所有阶段的有效循环次数和间隔时间", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (isAllMonitoring || isBootMonitoring || isStreamMonitoring || isSensorMonitoring)
                {
                    MessageBox.Show("已有监控在运行中", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                AddLog("=== 开始全部监控 ===");
                AddLog($"Boot阶段: 循环次数 {bootLoopCount}, 间隔 {bootInterval}ms");
                AddLog($"出图阶段: 循环次数 {streamLoopCount}, 间隔 {streamInterval}ms");
                AddLog($"Sensor阶段: 循环次数 {sensorLoopCount}, 间隔 {sensorInterval}ms");

                isAllMonitoring = true;
                UpdateButtonStates();




                try
                {
                    // 执行Boot监控
                    AddLog("=== 开始Boot阶段监控 ===");
                    await Task.Run(() => ExecuteBootMonitoring(bootLoopCount, bootInterval));
                    AddLog("=== Boot阶段监控完成 ===");

                    if (cancellationTokenSource.Token.IsCancellationRequested)
                        throw new OperationCanceledException();

                    // 执行出图监控
                    AddLog("=== 开始出图阶段监控 ===");
                    await Task.Run(() => ExecuteStreamMonitoring(streamLoopCount, streamInterval));
                    AddLog("=== 出图阶段监控完成 ===");

                    if (cancellationTokenSource.Token.IsCancellationRequested)
                        throw new OperationCanceledException();

                    // 执行Sensor监控
                    AddLog("=== 开始Sensor阶段监控 ===");
                    await Task.Run(() => ExecuteSensorMonitoring(sensorLoopCount, sensorInterval));
                    AddLog("=== Sensor阶段监控完成 ===");

                    AddLog("=== 全部监控完成 ===");
                    MessageBox.Show("全部监控已完成", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (OperationCanceledException)
                {
                    AddLog("全部监控已取消");
                }
                finally
                {
                    isAllMonitoring = false;
                    UpdateButtonStates();
                    // 重置取消标记
                    cancellationTokenSource = new CancellationTokenSource();
                }

            }
            else
            {
                // 用户取消操作
                MessageBox.Show("导出操作已取消", "提示",
                               MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void StopAllMonitoring_Click(object sender, RoutedEventArgs e)
        {
            if (isAllMonitoring || isBootMonitoring || isStreamMonitoring || isSensorMonitoring)
            {
                cancellationTokenSource.Cancel();
                AddLog("正在停止所有监控...");
            }
            else
            {
                AddLog("没有正在运行的监控");
            }
        }

        // 更新按钮状态
        private void UpdateButtonStates()
        {
            Dispatcher.Invoke(() =>
            {
                bool anyMonitoring = isBootMonitoring || isStreamMonitoring || isSensorMonitoring || isAllMonitoring;

                // 更新开始按钮状态
                btnStartBoot.IsEnabled = !anyMonitoring;
                btnStartStream.IsEnabled = !anyMonitoring;
                btnStartSensor.IsEnabled = !anyMonitoring;
                btnStartAll.IsEnabled = !anyMonitoring;

                // 更新停止按钮状态
                btnStopBoot.IsEnabled = isBootMonitoring || isAllMonitoring;
                btnStopStream.IsEnabled = isStreamMonitoring || isAllMonitoring;
                btnStopSensor.IsEnabled = isSensorMonitoring || isAllMonitoring;
                btnStopAll.IsEnabled = anyMonitoring;

                // 更新其他按钮状态
                btnExportAllExcel.IsEnabled = !anyMonitoring;
                //btnBaseAddress.IsEnabled = !anyMonitoring;
                //btnRefreshUsb.IsEnabled = !anyMonitoring;
                //btnOpenDevice.IsEnabled = !anyMonitoring;
                //btnCloseDevice.IsEnabled = !anyMonitoring;
            });
        }

        /// <summary>
        /// 导入EXCEL配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImportExcelButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Excel文件 (*.xlsx)|*.xlsx|Excel 97-2003文件 (*.xls)|*.xls|所有文件 (*.*)|*.*",
                Title = "选择维测信息Excel文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    _allRegisters = ParseExcelToRegisterInfo(openFileDialog.FileName);

                    // 导入后自动应用当前基地址
                    string baseAddressText = txtbaseAddress.Text.Trim();
                    if (!string.IsNullOrEmpty(baseAddressText))
                    {
                        UpdateBaseAddress(baseAddressText);
                    }
                    // 调用 RegisterInfoData 保存JSON数据
                    RegisterInfoData.UpdateRegisters(_allRegisters);
                    MessageBox.Show($"成功导入 {_allRegisters.Count} 个寄存器信息", "导入成功",
                                  MessageBoxButton.OK, MessageBoxImage.Information);
                    AddLog($"成功导入Excel文件: {openFileDialog.FileName}, 共{_allRegisters.Count}个寄存器");

                    // 更新配置状态显示
                    UpdateConfigStatus();

                   
                    // 显示导入的数据结构
                    var groupedByCategory = _allRegisters.GroupBy(r => r.Category);
                    foreach (var group in groupedByCategory)
                    {
                        AddLog($"\n--- {group.Key} ({group.Count()}个寄存器) ---");

                        foreach (var register in group)
                        {
                            string arrayInfo = register.IsArray ? $", 数组[{register.ArraySize}]" : "";
                            string parameterInfo = string.IsNullOrEmpty(register.Parameter) ? "" : $", 参数: {register.Parameter}";

                            AddLog($"{register.LogInfo} (缩写:{register.Abbreviation}, 地址:{register.RegisterAddress}, 位宽:{register.BitWidth}位, 寄存器数:{register.RegisterCount}{arrayInfo}{parameterInfo})");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入Excel失败: {ex.Message}", "错误",
                                  MessageBoxButton.OK, MessageBoxImage.Error);
                    AddLog($"导入Excel失败: {ex.Message}");
                }
            }
        }
        
        
        
        // 解析Excel文件生成RegisterInfo列表
        private List<RegisterInfo> ParseExcelToRegisterInfo(string filePath)
        {
            List<RegisterInfo> registers = new List<RegisterInfo>();

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook;
                if (filePath.ToLower().EndsWith(".xls"))
                {
                    workbook = new HSSFWorkbook(fs); // xls 格式
                }
                else
                {
                    workbook = new XSSFWorkbook(fs); // xlsx 格式
                }

                // 只有一个工作表，直接获取第一个工作表
                ISheet sheet = workbook.GetSheetAt(0);
                if (sheet == null)
                {
                    throw new Exception("Excel文件中没有找到工作表");
                }

                // 解析整个工作表，根据阶段标题分组
                ParseSingleSheet(sheet, registers);
            }

            return registers;
        }
        
        
        // 解析单个工作表，根据阶段标题分组
        private void ParseSingleSheet(ISheet sheet, List<RegisterInfo> registers)
        {
            string currentCategory = "";
            string currentRegister = "";
            string currentBitField = "";
            string currentAddress = "";

            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null) continue;

                // 读取各列数据
                string cell0 = GetCellStringValue(row.GetCell(0)); // log信息
                string cell1 = GetCellStringValue(row.GetCell(1)); // 寄存器地址
                string cell2 = GetCellStringValue(row.GetCell(2)); // 参数
                string cell3 = GetCellStringValue(row.GetCell(3)); // 释义
                string cell4 = GetCellStringValue(row.GetCell(4)); // 备注

                // 检查是否是阶段标题行
                if (IsStageTitle(cell0))
                {
                    currentCategory = ExtractCategory(cell0);
                    AddLog($"检测到阶段: {currentCategory}");
                    continue;
                }

                // 跳过空行和表头行
                if (string.IsNullOrEmpty(currentCategory) || IsHeaderRow(cell0, cell1, cell2, cell3, cell4))
                    continue;

                // 如果log信息不为空，更新当前寄存器和位域
                if (!string.IsNullOrEmpty(cell0) && !IsParameterRow(cell0))
                {
                    currentRegister = cell0;
                    currentAddress = cell1;

                    // 从log信息中提取位域
                    var bitFieldMatch = System.Text.RegularExpressions.Regex.Match(cell0, @"\[([0-9:]+)\]");
                    if (bitFieldMatch.Success)
                    {
                        currentBitField = bitFieldMatch.Value;
                    }
                    else
                    {
                        currentBitField = "";
                    }

                    // 如果当前行就有参数，直接创建记录
                    if (!string.IsNullOrEmpty(cell2))
                    {
                        RegisterInfo info = CreateRegisterInfo(
                            currentCategory, currentRegister, currentAddress, cell2,
                            cell3, cell4, currentBitField
                        );
                        registers.Add(info);
                    }
                    else
                    {
                        // 对于没有参数的寄存器（如Rtl_Mode_EN[31:0]），也创建记录
                        RegisterInfo info = CreateRegisterInfo(
                            currentCategory, currentRegister, currentAddress, "",
                            "", cell4, currentBitField
                        );
                        registers.Add(info);
                    }
                }
                else if (!string.IsNullOrEmpty(cell1) && string.IsNullOrEmpty(cell0))
                {
                    // 如果只有地址列有值（如0x8050013f这种情况），更新地址
                    currentAddress = cell1;
                }
                else if (!string.IsNullOrEmpty(cell2) && !string.IsNullOrEmpty(currentRegister))
                {
                    // 参数行：使用当前的寄存器信息，创建新记录
                    RegisterInfo info = CreateRegisterInfo(
                        currentCategory, currentRegister, currentAddress, cell2,
                        cell3, cell4, currentBitField
                    );
                    registers.Add(info);
                }
            }
        }

        // 判断是否是阶段标题行
        private bool IsStageTitle(string cellValue)
        {
            if (string.IsNullOrEmpty(cellValue)) return false;

            return cellValue.Contains("阶段维测信息") ||
                   cellValue.Contains("Sensor维测信息") ||
                   cellValue.Contains("主机交互维测信息");
        }
        // 从阶段标题中提取类别名称
        private string ExtractCategory(string stageTitle)
        {
            if (stageTitle.Contains("Boot阶段")) return "Boot阶段";
            if (stageTitle.Contains("出图阶段")) return "出图阶段";
            if (stageTitle.Contains("Sensor维测信息")) return "Sensor阶段";
            if (stageTitle.Contains("主机交互维测信息")) return "主机交互阶段";
            return stageTitle;
        }
        // 判断是否是表头行
        private bool IsHeaderRow(string cell0, string cell1, string cell2, string cell3, string cell4)
        {
            return cell0 == "log信息" && cell1 == "寄存器地址（字节序为小端）" &&
                   cell2 == "参数" && cell3 == "释义" && cell4 == "备注";
        }

        // 判断是否是参数行（主要是位定义行，如[0]检测Flash内容是否异常）
        private bool IsParameterRow(string cellValue)
        {
            if (string.IsNullOrEmpty(cellValue)) return false;
            return cellValue.StartsWith("[") && cellValue.Contains("]");
        }

        // 创建RegisterInfo对象并填充所有属性
        private RegisterInfo CreateRegisterInfo(string category, string logInfo, string address,
                                              string parameter, string description, string remark, string bitField)
        {
            //RegisterAddress 不进行从excel 表格获取地址  需要自动计算地址
            RegisterInfo info = new RegisterInfo
            {
                Category = category,
                LogInfo = logInfo,
                RegisterAddress = "",
                Parameter = parameter,
                Description = description,
                Remark = remark
            };

            // 解析位域和位宽
            ParseBitFieldAndWidth(info, bitField);

            // 生成缩写
            info.Abbreviation = GenerateAbbreviation(logInfo);

            // 解析寄存器数量和数组信息
            ParseRegisterCountAndArrayInfo(info);

            return info;
        }

        // 解析位域和位宽
        private void ParseBitFieldAndWidth(RegisterInfo info, string bitField)
        {
            // 优先从bitField参数解析
            if (!string.IsNullOrEmpty(bitField))
            {
                var match = System.Text.RegularExpressions.Regex.Match(bitField, @"\[(\d+):(\d+)\]");
                if (match.Success)
                {
                    int highBit = int.Parse(match.Groups[1].Value);
                    int lowBit = int.Parse(match.Groups[2].Value);
                    info.BitWidth = highBit - lowBit + 1;
                    return;
                }
            }

            // 如果bitField为空，从LogInfo中解析
            if (!string.IsNullOrEmpty(info.LogInfo))
            {
                var match = System.Text.RegularExpressions.Regex.Match(info.LogInfo, @"\[(\d+):(\d+)\]");
                if (match.Success)
                {
                    int highBit = int.Parse(match.Groups[1].Value);
                    int lowBit = int.Parse(match.Groups[2].Value);
                    info.BitWidth = highBit - lowBit + 1;
                    return;
                }

                // 尝试其他格式的位域
                match = System.Text.RegularExpressions.Regex.Match(info.LogInfo, @"\[(\d+)\]");
                if (match.Success)
                {
                    info.BitWidth = int.Parse(match.Groups[1].Value);
                    return;
                }
            }

            // 默认值
            if (info.LogInfo?.Contains("32") == true || info.Parameter?.Contains("31:0") == true)
                info.BitWidth = 32;
            else if (info.LogInfo?.Contains("8") == true || info.Parameter?.Contains("7:0") == true)
                info.BitWidth = 8;
            else if (info.LogInfo?.Contains("16") == true || info.Parameter?.Contains("15:0") == true)
                info.BitWidth = 16;
            else if (info.LogInfo?.Contains("24") == true || info.Parameter?.Contains("23:0") == true)
                info.BitWidth = 24;
            else
                info.BitWidth = 32; // 默认32位
        }

        // 生成缩写
        private string GenerateAbbreviation(string logInfo)
        {
            if (string.IsNullOrEmpty(logInfo)) return "";

            // 移除位域信息
            string cleanName = System.Text.RegularExpressions.Regex.Replace(logInfo, @"\[.*?\]", "").Trim();

            // 如果是数组，移除数组大小
            cleanName = System.Text.RegularExpressions.Regex.Replace(cleanName, @"\[\d+\]", "").Trim();

            // 取首字母大写
            if (cleanName.Length > 0)
            {
                return char.ToUpper(cleanName[0]) + cleanName.Substring(1);
            }

            return cleanName;
        }

        // 解析寄存器数量和数组信息
        private void ParseRegisterCountAndArrayInfo(RegisterInfo info)
        {
            // 检查是否为数组（如resetverd1[10]）
            var arrayMatch = System.Text.RegularExpressions.Regex.Match(info.LogInfo, @"(\w+)\[(\d+)\]");
            if (arrayMatch.Success && !info.LogInfo.Contains(":")) // 排除位域情况
            {
                info.IsArray = true;
                info.ArraySize = int.Parse(arrayMatch.Groups[2].Value);
                info.ArrayElementSize = 1; // 默认每个元素占用1个寄存器

                // 根据位宽调整元素大小
                if (info.BitWidth > 32)
                    info.ArrayElementSize = (info.BitWidth + 31) / 32; // 向上取整

                info.RegisterCount = info.ArraySize * info.ArrayElementSize;
            }
            else
            {
                info.IsArray = false;
                info.ArraySize = 1;
                info.ArrayElementSize = 1;

                // 根据位宽计算需要的寄存器数量
                if (info.BitWidth <= 32)
                    info.RegisterCount = 1;
                else
                    info.RegisterCount = (info.BitWidth + 31) / 32; // 向上取整
            }

            // 处理地址范围（如0x80280014-0x80280016）
            if (!string.IsNullOrEmpty(info.RegisterAddress) && info.RegisterAddress.Contains("-"))
            {
                var addresses = info.RegisterAddress.Split('-');
                if (addresses.Length == 2)
                {
                    try
                    {
                        ulong startAddr = Convert.ToUInt64(addresses[0].Trim(), 16);
                        ulong endAddr = Convert.ToUInt64(addresses[1].Trim(), 16);
                        int addressCount = (int)((endAddr - startAddr) / 4) + 1; // 假设4字节对齐
                        info.RegisterCount = Math.Max(info.RegisterCount, addressCount);
                    }
                    catch
                    {
                        // 转换失败，忽略
                    }
                }
            }
        }

        // 辅助方法：获取单元格的字符串值
        private string GetCellStringValue(ICell cell)
        {
            if (cell == null) return string.Empty;

            switch (cell.CellType)
            {
                case CellType.String:
                    return cell.StringCellValue?.Trim() ?? "";
                case CellType.Numeric:
                    return cell.NumericCellValue.ToString();
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Formula:
                    try
                    {
                        return cell.StringCellValue?.Trim() ?? "";
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
                default:
                    return "";
            }
        }

        // 清除导入的Excel配置
        private void ClearImportButton_Click(object sender, RoutedEventArgs e)
        {
            if (_allRegisters != null && _allRegisters.Count > 0)
            {
                var result = MessageBox.Show("确定要清除导入的Excel配置吗？清除后将使用默认配置。",
                    "确认清除", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    _allRegisters.Clear();
                    _allRegisters = null;
                    AddLog("已清除导入的Excel配置，将使用默认配置");

                    // 重新应用基地址到默认配置
                    string baseAddressText = txtbaseAddress.Text.Trim();
                    if (!string.IsNullOrEmpty(baseAddressText))
                    {
                        UpdateBaseAddress(baseAddressText);
                    }

                    // 更新配置状态显示
                    UpdateConfigStatus();
                }
            }
            else
            {
                AddLog("当前没有导入的Excel配置");
            }
        }

        /// <summary>
        /// 更新配置状态显示
        /// </summary>
        private void UpdateConfigStatus()
        {
            Dispatcher.Invoke(() =>
            {
                if (_allRegisters != null && _allRegisters.Count > 0)
                {
                    txtConfigStatus.Text = "导入的Excel配置";
                    txtConfigStatus.Foreground = System.Windows.Media.Brushes.Green;
                }
                else
                {
                    txtConfigStatus.Text = "默认配置";
                    txtConfigStatus.Foreground = System.Windows.Media.Brushes.Blue;
                }
            });
        }

        /// <summary>
        /// 获取当前配置来源描述
        /// </summary>
        private string GetConfigSourceDescription()
        {
            return _allRegisters != null && _allRegisters.Count > 0 ? "导入的Excel配置" : "默认配置";
        }

        /// <summary>
        /// 检查设备是否已打开
        /// </summary>
        private bool CheckDeviceOpened(string operationName)
        {
            // 检查串口设备是否打开
            if (SerialPort == null || !SerialPort.DeviceStatus())
            {
                string errorMsg = $"执行{operationName}前请先打开USB设备";
                MessageBox.Show(errorMsg, "设备未打开", MessageBoxButton.OK, MessageBoxImage.Warning);
                AddLog(errorMsg);
                return false;
            }
            return true;
        }

        #region i2c 控制



        private void ControlType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {    // 添加空值检查，避免异常
            if (usbControlPanel == null || i2cControlPanel == null)
            {
                // 可以在这里添加调试信息或日志
                System.Diagnostics.Debug.WriteLine("控件未初始化");
                return;
            }
            if (cmbControlType.SelectedItem is ComboBoxItem selectedItem)
            {
                string controlType = selectedItem.Content.ToString();

                if (controlType == "USB设备控制")
                {
                    usbControlPanel.Visibility = Visibility.Visible;
                    i2cControlPanel.Visibility = Visibility.Collapsed;
                    // 可以在这里添加其他USB相关的初始化代码
                    serialPortManager = new SerialPort_Usb_RegisterManager();
                    NavigationService.Initialize(serialPortManager);
                }
                else if (controlType == "I2C设备控制")
                {
                    usbControlPanel.Visibility = Visibility.Collapsed;
                    i2cControlPanel.Visibility = Visibility.Visible;
                    // 可以在这里添加其他I2C相关的初始化代码
                    serialPortManager = new SerialPort_CH341_I2CManager();
                    NavigationService.Initialize(serialPortManager);
                }
            }
        }

        // 获取当前设备类型
        private DeviceControlType GetCurrentDeviceControlType()
        {
            try
            {
                return cmbControlType.Dispatcher.Invoke(() =>
                {
                    if (cmbControlType.SelectedItem is ComboBoxItem selectedItem && selectedItem.Content != null)
                    {
                        string controlType = selectedItem.Content.ToString();
                        return controlType == "I2C设备控制" ? DeviceControlType.I2C : DeviceControlType.USB;
                    }
                    return DeviceControlType.USB; // 默认值
                });
            }
            catch (Exception ex)
            {
                // 记录异常并返回默认值
                System.Diagnostics.Debug.WriteLine($"获取设备控制类型时出错: {ex.Message}");
                return DeviceControlType.USB;
            }
        }

        private void SearchI2CAddress_Click(object sender, RoutedEventArgs e)
        {
            // 添加设备检查
            if (!CheckDeviceOpened("I2C设备"))
            {
                return;
            }

            // 清空现有的地址列表
            cmbI2CAddress.Items.Clear();

            // 搜索I2C地址
            List<string> i2cList = new List<string>();
            for (uint i = 0; i < 0xff; i++)
            {
                SerialPort.SetDeviceConfig(Convert.ToInt32(cmbI2CBus.Text), i);
                var values = SerialPort.ReadRegister(0, out string msg);
                if (values != null && values.Count > 0 && values[0] != 0xff && (i % 2) == 0)
                {
                    string addr = "0x" + i.ToString("X2");
                    i2cList.Add(addr);
                }
            }


            if (i2cList.Count == 0)
            {
                AddLog("USB设备列表已刷新，但未找到任何USB设备");
                MessageBox.Show("未找到任何USB设备！\n\n请检查：\n• USB设备是否已连接\n• 驱动程序是否已安装\n• 设备管理器中的端口状态",
                              "未找到设备",
                              MessageBoxButton.OK,
                              MessageBoxImage.Warning);
                return;
            }

            // 将搜索到的地址添加到ComboBox
            foreach (string addr in i2cList)
            {
                cmbI2CAddress.Items.Add(addr);
            }

            // 如果搜索到设备，选择第一个设备
            if (cmbI2CAddress.Items.Count > 0)
            {
                cmbI2CAddress.SelectedIndex = 0;
            }

        }

        private void cmbI2CAddress_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbI2CAddress.SelectedItem != null)
            {
                string selectedAddress = cmbI2CAddress.SelectedItem.ToString();

                try
                {
                    // 移除"0x"前缀
                    string cleanAddress = selectedAddress;
                    if (cleanAddress.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                    {
                        cleanAddress = cleanAddress.Substring(2);
                    }

                    // 转换为数值
                    uint addressValue = Convert.ToUInt32(cleanAddress, 16); // 使用16进制转换

                    // 获取总线号
                    int busNumber = 0;
                    if (int.TryParse(cmbI2CBus.Text, out busNumber))
                    {
                        SerialPort.SetDeviceConfig(busNumber, addressValue);
                        AddLog($"I2C配置已更新: 总线 {busNumber}, 地址 0x{addressValue:X2}");
                    }
                    else
                    {
                        AddLog("无效的总线号");
                    }
                }
                catch (Exception ex)
                {
                    AddLog($"设置I2C配置失败: {ex.Message}");
                }
            }

        }

        /// <summary>
        /// 设置 StreamOn 寄存器值
        /// </summary>
        private void SetStreamOnRegister()
        {
            try
            {
                // 获取当前设备类型
                var currentControlType = GetCurrentDeviceControlType();

                // 只在 I2C 模式下设置寄存器
                if (currentControlType != DeviceControlType.I2C)
                {
                    AddLog("仅在 I2C 设备模式下需要设置 StreamOn 寄存器");
                    return;
                }

                // 使用动态寄存器源
                var currentRegisters = GetCurrentRegisters();

                // 查找 IsStreamOn[7:0] 寄存器
                var streamOnRegister = currentRegisters
                    .FirstOrDefault(r => r.LogInfo == "IsStreamOn[7:0]");

                if (streamOnRegister == null)
                {
                    AddLog("未找到 IsStreamOn[7:0] 寄存器");
                    return;
                }

                // 解析地址
                string addressStr = streamOnRegister.RegisterAddress;
                if (addressStr.Contains('-'))
                {
                    addressStr = addressStr.Split('-')[0].Trim(); // 取地址范围的起始地址
                }

                addressStr = addressStr.Replace("0x", ""); // 移除 0x 前缀

                if (ulong.TryParse(addressStr, NumberStyles.HexNumber, null, out ulong address))
                {
                    SerialPort.WriteRegister(address, new List<ulong> { 0x01 }, out string msg);
                    AddLog($"设置 IsStreamOn[7:0] 寄存器 (地址 0x{address:X8}) 为 0x01: {msg}");
                }
                else
                {
                    AddLog($"无法解析寄存器地址: {streamOnRegister.RegisterAddress}");
                }
            }
            catch (Exception ex)
            {
                AddLog($"设置 StreamOn 寄存器时出错: {ex.Message}");
            }
        }


        #endregion


    }


    // 定义设备类型枚举
    public enum DeviceControlType
    {
        USB,
        I2C
    }
    // 数据模型类
    public class UsbDeviceInfo
    {
        public string DeviceName { get; set; }
        public string DeviceId { get; set; }
        public string Status { get; set; }
    }

    // Boot监控结果类
    public class BootMonitorResult
    {
        public string RegisterAddress { get; set; }
        public string Value { get; set; }  // 字段内容，如 "0x12345678"
        public List<string> Errors { get; set; }  // 错误列表
        public DateTime Timestamp { get; set; }  // 时间戳
        public bool HasError { get; set; }  // 是否存在错误

        public uint SortAddress { get; set; } // 排序用的地址
        public int LoopIndex { get; set; }  // 新增：循环索引
        public BootMonitorResult()
        {
            Errors = new List<string>();
            HasError = false;
        }
    }
}